/*!
 * Custom html dom resize handler event
 * version: 1.1.0
 */

// AMD support
(function (factory){
    "use strict";
    
    if (typeof define === 'function' && define.amd) {
        define(['jquery'], factory);
    } else {
        factory( (typeof(jQuery) != 'undefined') ? jQuery : window.Zepto );
    }
}(function($) {
	"use strict";
	
	var elems = jQuery([]), timeout_id,
		str_data = 'resize-special-event',
		str_delay = 'delay',
		str_resize = 'handlerResize',
		str_throttle = 'throttleWindow',
		str_setTimeout = 'setTimeout';
	
	var handlerResize = jQuery.extend(jQuery.resize, {});
	
	handlerResize[str_delay] = 250;
	handlerResize[str_throttle] = true;
	  
	jQuery.event.special[str_resize] = {
		setup: function() {
			if (!handlerResize[str_throttle] && this[str_setTimeout]) { return false; }
	      
			var elem = jQuery(this);
	      
			elems = elems.add(elem);
	      
			jQuery.data(this, str_data, {w: elem.width(), h: elem.height()});
	      
			if (elems.length === 1) { loopy(); }
	    },
	    teardown: function() {
	    	if (!handlerResize[str_throttle] && this[str_setTimeout]) { return false; }
	      
	    	var elem = jQuery(this);
	      
	    	elems = elems.not(elem);
	      
	    	elem.removeData(str_data);
	      
	    	if (!elems.length) { clearTimeout(timeout_id); }
	    },
	    add: function( handleObj ) {
	    	if (!handlerResize[str_throttle] && this[str_setTimeout]) { return false; }
	      
	    	var old_handler;
	      
	    	function new_handler( e, w, h ) {
		        var elem = jQuery(this),
		        	data = jQuery.data( this, str_data );
		        
		        data.w = w !== undefined ? w : elem.width();
		        data.h = h !== undefined ? h : elem.height();
		        
		        old_handler.apply( this, arguments );
	    	};
	    	
	    	if ( jQuery.isFunction( handleObj ) ) {
		        old_handler = handleObj;
		        return new_handler;
	    	} else {
		        old_handler = handleObj.handler;
		        handleObj.handler = new_handler;
	    	}
	    }
	};
	
	function loopy() {
		timeout_id = window[str_setTimeout](function(){
			elems.each(function(){
				var elem = jQuery(this),
	        		width = elem.width(),
	        		height = elem.height(),
	        		data = jQuery.data(this, str_data);
				
				if ( width !== data.w && height !== data.h) {
					elem.trigger( str_resize, [ data.w = width, data.h = height, "width" ] );
				}else if(height !== data.h ){
					elem.trigger( str_resize, [ data.w = width, data.h = height, "height" ] );
				}
	      });
			
	      loopy();
	      
	    }, handlerResize[str_delay]);
	    
	};
}));
